$(document).ready(function(){	
	//photoGridAjaxEvent('#photos', 'displayLastPopular/10/1/');
	
	$('#nbPhotos').live('change', function() {
		var div = $(this).attr('type');
		var typeMethod = $('#'+div).attr('type');
		var nbPhotoToDisplay = $(this).val();
		var currentPage = $('#currentPage').attr('src');
		photoGridAjaxEvent('#'+div, typeMethod+'/'+nbPhotoToDisplay+'/'+currentPage+'/');
	});
	
	$('.paginationBt').live('click', function() {
		var div = $(this).parent().attr('src');
		//alert(div);
		var typeMethod = $(this).parent().attr('type');
		//alert(typeMethod);
		var nbPhotoToDisplay = $('#'+div).next().children('form').children('select').val();
		var newPage = $(this).attr('src');
		photoGridAjaxEvent('#'+div, typeMethod+'/'+nbPhotoToDisplay+'/'+newPage+'/');
	});
	
	$('.gridElement').live('mouseenter', function() {
		$(this).children('.gridInfo').animate({opacity: 1 }, 200, function() {});
	});
	
	$('.gridElement').live('mouseleave', function() {
		$(this).children('.gridInfo').animate({opacity: 0 }, 200, function() {});
	});
	
	$(".barreMoreComm").live("click", function() {
		var numPhoto = $(this).attr("rel");
		$("#commentairesPhoto"+numPhoto+" .commentaireHide").css("display", "block");
		$(this).css("display", "none");
	});
	
	$(".gridInfo .whiteBorder[rel]").live("click", function(){
		var idPhoto = $(this).attr('rel').substring(6);
		$("#lazy"+idPhoto).lazyload();
	});
	
	$('.addComm .submit-post').live('click', function(){
		var idPhoto = $(this).attr('id').substring(11);
		var form = $("#form"+idPhoto);

		var _comment = form.find('textarea[name="comment"]').val();
		if( _comment == "" || _comment == "Ecrivez votre commentaire" ){
			$( "#result"+idPhoto ).empty().append( "Commentaire non valide." );
		}
		else{
			var _csrfmiddlewaretoken = form.find('input[name="csrfmiddlewaretoken"]').val();
			var _content_type = form.find('input[name="content_type"]').val();
			var _object_pk = form.find('input[name="object_pk"]').val();
			var _timestamp = form.find('input[name="timestamp"]').val();
			var _security_hash = form.find('input[name="security_hash"]').val();
			var _name = form.find('input[name="name"]').val();
			var _email = form.find('input[name="email"]').val();
			var _url = form.find('input[name="url"]').val();
			
			var datas = { csrfmiddlewaretoken:_csrfmiddlewaretoken, content_type:_content_type, object_pk:_object_pk, timestamp:_timestamp, security_hash:_security_hash, name:_name, email:_email, url:_url, comment:_comment};
			$.post( form.attr('action'), datas,
				function( data ) {
					//$( "#result"+idPhoto ).empty().append(  "Commentaire bien envoy&eacute;" );
				}
			); 
			updateCommentsList(idPhoto, 1);
		}
	});
	
});

function updateCommentsList(idPhoto, displayAll){
	photoGridAjaxEvent("#commentsList"+idPhoto, "getPhotoComments/"+idPhoto+"/"+displayAll);
}

function resetCommDisplay(numPhoto){
	$(".commentaireHide").css("display", "none");
	$(".barreMoreComm").css("display", "block");
}

function initMap(view, zoomed, zoomLevel, zoomLat, zoomLong, idAlbum){
	var so = new SWFObject("/media/ammap/ammap.swf", "ammap", "100%", "100%", "8", "#E7CC9F");
	so.addVariable("path", "/media/ammap/");
	so.addVariable("map_id", "ammap");
	if (view == "home" || view == "search"){
		so.addVariable("data_file", escape("/media/ammap/ammap_data_big.xml"));
		so.addVariable("settings_file", escape("/media/ammap/ammap_settings_big.xml"));	
		g_view = view;
	}
	if (view == "profile" || view == "add"){
		so.addVariable("data_file", escape("/media/ammap/ammap_data_small.xml"));
		so.addVariable("settings_file", escape("/media/ammap/ammap_settings_small.xml"));
		g_view = view;
	}
	g_zoomed = zoomed;
	g_zoomLevel = zoomLevel;
	g_zoomLat = zoomLat;
	g_zoomLong = zoomLong;
	g_idAlbum = idAlbum;
	so.addVariable("preloader_color", "#999999");
	so.write("flashcontent");
	firstLoading = true;
	homeLoading = true;
	countryLoading = false;
}

function amReturnData(map_id, data){
	g_data=unescape(data);
}

function amMapCompleted(map_id){
	if (firstLoading){
		firstLoading = false;
		flashMovie = document.getElementById(map_id);
		if (g_zoomed == 1){
			
			flashMovie.setZoomLongLat(g_zoomLevel, g_zoomLat, g_zoomLong);
		}
		var movies = "<movies>";
		// on ajoute un movie bidon pour qu'il soit jamais vide	
		movies += "<movie title='dummy_movie' file='target' color='#da4b26' height='10' width='10' lat='-5000' long='50' fixed_size='true'></movie>"

		movies += "</movies>";
		addDataToMap(movies);
		if (g_view == "home"){
			$.ajax({
			   url: "getPhotoCoords/0/",
			   success : function(data){
					readPhotoData(data, true);
			   }
			});	
		}
		else if (g_view == "profile"){
			$.ajax({
			   url : "getVisitedCountries/"+idPhotographer,
			   success : function(data){
					if (g_idAlbum != 0){
						$.ajax({
						   url: "getPhotoCoordsByAlbum/"+g_idAlbum+"/",
						   success : function(data){
								readPhotoData(data, true);
						   }
						});	
					}
					readVisitedCountriesData(data);					
			   }
			});
		}
		else if (g_view == "search"){
			readResultSearch();
		}
	}
}

function readResultSearch(){
	flashMovie.getData();
	var new_data = g_data;
	var movies = "<movies>";
	// on ajoute un movie bidon pour qu'il soit jamais vide
	movies += "<movie title='dummy_movie' file='target' color='#ff0000' height='10' width='10' lat='-5000' long='5000' fixed_size='true'></movie>"
	for (var i=0; i<photoTitles.length-1;i++) {
		movies += "<movie title='"+photoTitles[i]+"' file='circle' color='#da3f26' height='6' width='6' lat='" + photoLong[i]/100000000 +"' long='" + photoLat[i]/100000000 + "' url='/profile/"+photoPhotographer[i]+"/"+photoAlbum[i]+"' fixed_size='true'></movie>"
	}
	//alert(movies);
	addDataToMap(movies);
}

function readVisitedCountriesData(data){
	var nodes   = data.getElementsByTagName("country");
	flashMovie.getData();
	var new_data = g_data;
	for (var i=0, c=nodes.length; i<c; i++) {
		
		var countryId = nodes[i].getAttribute("id");
		var patt=new RegExp('<area zoom="[0-9]*.?[0-9]*%" zoom_x="-?[0-9]*.?[0-9]*%" zoom_y="-?[0-9]*.?[0-9]*%" color="#[0-9]{6}" title="[A-z| ]*" mc_name="[A-z]*" oid="'+countryId+'"');
		var countryLine = new String(new_data.match(patt));
		var pattColor = new RegExp('#[0-9]{6}');
		countryLine = countryLine.replace(pattColor, "#5e8c99");
		new_data = new_data.replace(patt, countryLine);
	}
	flashMovie.setData(new_data);
}

function readPhotoData(data, homeLoading){
	var nodes   = data.getElementsByTagName("photo");
	var movies = "<movies>";
	// on ajoute un movie bidon pour qu'il soit jamais vide
	movies += "<movie title='dummy_movie' file='target' color='#ff0000' height='10' width='10' lat='-5000' long='50' fixed_size='true'></movie>"
	
	
	for (var i=0, c=nodes.length; i<c; i++) {
		if (homeLoading && g_view == 'home'){
			movies += "<movie file='circle' color='#da3f26' height='4' width='4' lat='" + nodes[i].getAttribute("latitude") +"' long='" + nodes[i].getAttribute("longitude") + "' fixed_size='true'></movie>"
		}
		else {
				//si une seule photo a ces coordonnees : redirection vers l'album de cette photo
				if (nodes[i].getAttribute("nbPhotos") == 1){
					movies += "<movie title='" + nodes[i].getAttribute("nom") + "' file='circle' color='#da3f26' height='6' width='6' lat='" + nodes[i].getAttribute("latitude") +"' long='" + nodes[i].getAttribute("longitude") + "' fixed_size='true' ";
					if (g_view == "home"){
						movies += "url='/profile/"+nodes[i].getAttribute("photographerId")+"/"+nodes[i].getAttribute("albumId")+"'";
					}
					if (g_view == "profile"){
						movies += "url='' value='"+nodes[i].getAttribute("photographerId")+"/"+nodes[i].getAttribute("albumId")+"'";
					}
					movies += "></movie>";
				}
				//sinon : redirection vers recherche avec tous les albums avec ces coords (TODO)
				else {
					movies += "<movie title='" + nodes[i].getAttribute("nom") + "' file='circle' color='#da3f26' height='6' width='6' lat='" + nodes[i].getAttribute("latitude") +"' long='" + nodes[i].getAttribute("longitude") + "' fixed_size='true'></movie>";
				}

		}
	}
	
	movies += "</movies>";
	addDataToMap(movies);
}

function addDataToMap(data){
	flashMovie.getData();
	var patt=new RegExp("<movies>.*\n*(.*\n*)*\n*.*</movies>");
	var new_data = g_data.replace(patt, data);
	flashMovie.setData(new_data);
}

function amRegisterClick(map_id, object_id, title, value){
	if (object_id!=null){
		if (g_view == "profile" || g_view == "home"){
			if (object_id==0){
				homeLoading = true;
				flashMovie.getData();
				var patt=new RegExp("<text>.*</text>");
				var new_data = g_data.replace(patt, "<text><![CDATA[<b></b>]]></text>");
				flashMovie.setData(new_data);
				if (g_view == "home"){
					$.ajax({
					   url: "getPhotoCoords/"+object_id+"/",
					   success : function(data){
							readPhotoData(data, true);
					   }
					});
				}
				else if (g_view == "profile"){
					$.ajax({
					   url: "getPhotoCoords/111111/",
					   success : function(data){
							readPhotoData(data, true);
					   }
					});
					
				}
			}
			else {
				countryLoading = true;
				flashMovie.getData();
				var patt=new RegExp("<text>.*</text>");

				var new_data = g_data.replace(patt, "<text><![CDATA[<b>Revenir a la carte du monde</b>]]></text>");

				flashMovie.setData(new_data);
				if (g_view == "home"){
					$.ajax({
					   url: "getPhotoCoords/"+object_id+"/",
					   success : function(data){
							readPhotoData(data, false);
					   }
					});
				}
				else if (g_view == "profile"){
					$.ajax({
					   url: "getPhotoCoords/"+object_id+"/"+idPhotographer,
					   success : function(data){
							readPhotoData(data, false);
					   }
					});
				}
			}
		}
		else if (g_view == "add" && clickMap){
			if (object_id!=null){
				$('#id_city_id').val(object_id);
				$('#city_selected').html("La ville " + title + " a &eacute;t&eacute; s&eacute;lectionn&eacute;e.");
			}
		}
	}
}

function amRegisterClickAnywhere(map_id, object_id, title, value){
	if (value != null){
		photoGridAjaxEvent("#photos", "/displayAlbumPhoto/"+ value +"/20/1/");
	}
}

function amProcessCompleted(map_id, process_name){

}

function addToFavorite(photoId){
	$.ajax({
	   url: "addToFavorites/"+photoId,
	   success : function(data){
			$("#fav_photo_"+photoId).html("Retirer des favoris");
			$("#fav_photo_"+photoId).attr("onClick", "removeFromFavorite("+photoId+")");
		}
	});
}

function removeFromFavorite(photoId){
	$.ajax({
	   url: "removeFromFavorites/"+photoId,
	   success : function(data){
			$("#fav_photo_"+photoId).html("Ajouter aux favoris");
			$("#fav_photo_"+photoId).attr("onClick", "addToFavorite("+photoId+")");
		}
	});
}

function photoGridAjaxEvent(div, _url, profilPerso){
	if(profilPerso != undefined && profilPerso == true)
		_url += "1";  
		
	$.ajax({
	   url: _url,
		beforeSend: function( xhr ) {
			$(div).html("<div style=\"width:100%; height : 45px; margin-top : 20px; text-align:center;\"><img src=\"/media/img/loader.gif\" alt=\"loader\"</div>");
		},
	   success : function(data){
			$(div).html("");
			$(div).html(data);
		}
	});
}
